var start = ee.Date('2022-04-01');
var end = ee.Date('2022-10-31');
var interval = 30;
var roi = FJ_Edge;

// 云掩膜函数
function maskS2clouds(image) {
  var qa = image.select('QA60');
  var cloudBitMask = 1 << 10;
  var cirrusBitMask = 1 << 11;
  var mask = qa.bitwiseAnd(cloudBitMask).eq(0)
               .and(qa.bitwiseAnd(cirrusBitMask).eq(0));
  return image.updateMask(mask).copyProperties(image, ['system:time_start']);
}

// 指数计算函数
function addIndices(image) {
  var ndvi = image.normalizedDifference(['B8', 'B4']).rename('NDVI');
  var mndwi = image.normalizedDifference(['B3', 'B11']).rename('MNDWI');
  var lswi = image.normalizedDifference(['B8', 'B11']).rename('LSWI');
  var ndsvi = image.normalizedDifference(['B11', 'B4']).rename('NDSVI');
  var gcvi = image.expression('(NIR / GREEN) - 1', {
    NIR: image.select('B8'),
    GREEN: image.select('B3')
  }).rename('GCVI');

  return image.addBands([ndvi, mndwi, lswi, ndsvi, gcvi])
              .select(['NDVI', 'MNDWI', 'LSWI', 'NDSVI', 'GCVI']);
}

// 时间序列创建
var nImages = end.difference(start, 'day').divide(interval).floor();
var dates = ee.List.sequence(0, nImages.subtract(1)).map(function(i) {
  return start.advance(ee.Number(i).multiply(interval), 'day');
});

// 合成每30天的图像
var multiBandCollection = ee.ImageCollection(dates.map(function(date) {
  date = ee.Date(date);
  var filtered = ee.ImageCollection('COPERNICUS/S2_SR_HARMONIZED')
                    .filterBounds(roi)
                    .filterDate(date, date.advance(interval, 'day'))
                    .filter(ee.Filter.lt('CLOUDY_PIXEL_PERCENTAGE', 30))
                    .map(maskS2clouds)
                    .map(addIndices);
  var composite = filtered.median()
      .set('system:time_start', date.millis())
      .clip(roi)
      .reproject({crs: 'EPSG:4326', scale: 10});
  return composite;
}));

Map.centerObject(roi, 8);
Map.addLayer(roi, {palette: "ff0000"}, "ROI");

// 导出所有图像
var list = multiBandCollection.toList(multiBandCollection.size());
var n = list.size().getInfo();

for (var i = 0; i < n; i++) {
  var img = ee.Image(list.get(i));
  img = img.toFloat();
  Export.image.toDrive({
    image: img,
    description: 'MultiVIs_' + i,
    folder: 'MultiVIs_30day',
    fileNamePrefix: 'MultiVIs_' + i,
    region: roi,
    scale: 10,
    crs: 'EPSG:4326',
    maxPixels: 1e13
  });
}
